package com.mrlv.common.http;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class HttpPostUtil {

    public static JSONObject execute(String url, List<BasicNameValuePair> nvps) throws Exception {
        log.info("发送http  post请求 url :{}, 参数 ： {}", url, nvps);
        //获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //获取URL对象
        HttpPost post = new HttpPost(url);
        //自定义一个请求配置

        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();

        post.setConfig(config);
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // 设置参数给Post

        // 执行
        HttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            /**读取服务器返回过来的json字符串数据**/
            String str = EntityUtils.toString(entity);
            log.info("请求成功！结果 ： {}", str);
            return JSONUtil.parseObj(str);
        } else {
            log.info("请求失败");
            return null;
        }
    }


    public static void main(String[] args) throws Exception {
        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("appId", "jHB0O6j9"));
        nvps.add(new BasicNameValuePair("appKey", "nY8Retuh"));
        nvps.add(new BasicNameValuePair("mobile", "13120775975"));
        nvps.add(new BasicNameValuePair("templateId", "2678"));
        nvps.add(new BasicNameValuePair("param", "york.zhao,感受感受多过过所多军军军军军军"));
        nvps.add(new BasicNameValuePair("allowedCallTime", "58"));


        JSONObject jsonObject = HttpPostUtil.execute("https://api.253.com/open/notify/voice-notify", nvps);

        // 2.处理返回结果
        if (jsonObject != null) {
            //响应code码。200000：成功，其他失败
            String code = jsonObject.getStr("code");
            if ("200000".equals(code) && jsonObject.get("data") != null) {
                String content = jsonObject.get("data").toString();
                System.out.println("语音通知发送成功,content is :" + content);
            } else {
                // 记录错误日志，正式项目中请换成log打印
                System.out.println("语音通知发送失败,code:" + code + ",msg:" + jsonObject.getStr("message"));
            }
        }

    }


}
